import { defineStore } from "pinia";
import { store } from "@/store";
import { type userTokenType } from "../types";
import {
  getRSAKey,
  userLogin,
  LoginResponse,
  refreshTokenApi,
} from "@/api/user";
import {
  userKey,
  encryptByRSA,
  setToken,
  removeToken,
  type DataInfo,
} from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import router from "@/router";
export const useUserStore = defineStore({
  id: "user-token",
  state: (): userTokenType => ({
    accessToken: storageLocal().getItem<DataInfo<number>>(userKey)?.accessToken ?? "",
    refreshToken: storageLocal().getItem<DataInfo<number>>(userKey)?.refreshToken ?? "",
    expires: storageLocal().getItem<DataInfo<number>>(userKey)?.expires ?? 0,
  }),

  actions: {
    async logIn(data) {
      // 获取加密参数
      let resKey = await getRSAKey();
      // 加密数据
      let encryptData = encryptByRSA(resKey.publickey, JSON.stringify(data));
      // 发起登录请求
      return new Promise<LoginResponse>((resolve, reject) => {
        userLogin({ data: encryptData })
          .then((data) => {
            if (data?.status?.code == 200) {
              setToken(data.tokens);
              this.accessToken = data.tokens.token;
              this.refreshToken = data.tokens.refreshtoken;
            }
            resolve(data);
            //@ts-ignore
            ElMessage.success("登录成功");
            router.push("/");
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    
    /** 前端登出（不调用接口） */
    logOut() {
      removeToken();
      router.push("/login");
    },

    /**
     * @description: 刷新`token`
     * @param {object} refreshObj
     */
    async handRefreshToken(refreshObj: { refreshtoken: string }) {
      return new Promise<LoginResponse>((resolve, reject) => {
        refreshTokenApi(refreshObj)
          .then((data) => {
            if (data) {
              setToken(data.tokens);
              resolve(data);
            }
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
  },
});

export function useUserStoreHook() {
  return useUserStore(store);
}
